package com.example.security.custom;

import cn.hutool.json.JSONUtil;
import com.example.security.config.TokenService;
import com.example.security.dmo.SecurityUser;
import com.example.security.dmo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
public class AdminAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private TokenService tokenService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
        SecurityUser securityUser = ((SecurityUser) auth.getPrincipal());
        SysUser user = securityUser.getCurrentUserInfo();
        String token = tokenService.createToken(securityUser.getCurrentUserInfo());
        user.setToken(token);
        response.getOutputStream().write(JSONUtil.toJsonStr(user).getBytes());
    }
}